/*
 * Copyright (c) 2004-2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gou Pengfei
 * Date:    April. 2011
 */

#ifndef __CPU_EDGE_TOURNAMENT_FRAMEWORK_HH__
#define __CPU_EDGE_TOURNAMENT_FRAMEWORK_HH__

#include <vector>
#include <deque>

#include "base/types.hh"
#include "cpu/edge/sat_counter.hh"
#include "cpu/edge/pred/base_type_predictor.hh"
//#include "cpu/edge/pred/predictor_table.hh"
#include "config/the_isa.hh"
#include "arch/isa_traits.hh"
#include "params/DerivEdgeCPU.hh"

/**
 * A class to implement the framework of tournament predictors, for
 * which different predictors can be combined in an easy way.
 * */
template<class Impl>
class TournamentFramework : public BaseTypePredictor<Impl>
{
  public:
    typedef TheISA::BlockID BlockID;
    typedef TheISA::BTypeID BTypeID;

    enum TableMode {
        Normal,
        AliasFree,
        InvalidTableMode
    };

    TournamentFramework(DerivEdgeCPUParams *params);

    ~TournamentFramework();

    void reset();	

    /**
     * Lookup the given block address in the branch predictor and returns
     * an type ID of the block.
     */
    TheISA::BTypeID lookup(BlockID block_id, BlockID oldest_block_id, 
        Addr &block_addr, int addr_space_ID, ThreadID tid);   

    /**
     * Update the branch predictor with the actual result of a branch.
     */
    TheISA::BTypeID update(BlockID block_id, Addr &block_addr,
            int addr_space_id, BTypeID actual_type_id,ThreadID tid);

    /**
     * Restore the global branch history on a squash.
     */
    void squash(BlockID block_id, Addr block_pc, BTypeID type_id,
            ThreadID tid);

    /**
     * Restore the global branch history on a squash.
     */
    void squash(BlockID block_id, ThreadID tid);

    uint64_t lookupGetIndex(Addr &block_PC, ThreadID tid);

    uint64_t updateGetIndex(BlockID block_id, Addr &block_PC, ThreadID tid);

    void regStats();

    int getCounterBits() { return choiceCtrBits; }

  private:

    BaseTypePredictor<Impl> * predictor1;

    BaseTypePredictor<Impl> * predictor2;

    TableMode tableMode;

    struct PredictionTableEntry
    {
        PredictionTableEntry(BasePredictor<Impl> * ptr)
            : predictorPtr(ptr),
              counter(ptr->getCounterBits())
        {
        }

        ~PredictionTableEntry()
        {};

        void reset() { counter.reset(); }

        int read() { return counter.read(); }
        
        void setBits(int bits) { counter.setBits(bits); }

        void increment(int inc_num = 1) { counter.increment(inc_num); }

        void decrement(int dec_num = 1) { counter.decrement(dec_num); }

        BasePredictor<Impl> * predictorPtr;

        SatCounter counter;
    };

    void initVars();

    /** Calculate the index to the chooser. */
    inline uint64_t calcChoiPredIdx(Addr &block_addr, uint64_t history);

    /** Choice history register. */
    uint64_t choiceHistory[Impl::MaxThreads];

    /** Choice history file. */
    std::vector<uint64_t> choiceHistoryFile;

    /** Number of bits for the choice history. */
    uint64_t choiceHistoryBits;

    /** Mask to get the proper choice history. */
    uint64_t choiceHistoryMask;

    /** Number of bits of the choice predictor's counters. */
    int choiceCtrBits;

    /** Array of counters that make up the choice predictor. */
    PredictorTable<PredictionTableEntry, Impl> choiceCtrs;

    /** Size of the choice predictor (identical to the global predictor). */
    uint64_t choicePredictorSize;

    /** Mask of the choice predictor table. */
    uint64_t choicePredictorMask;

    /**
     * Number of bits to shift the instruction over to get rid of the word
     *  offset.
     */
    uint64_t blockShiftAmt;

    /**
     * Threshold for the counter value; above the threshold is taken,
     *  equal to or below the threshold is not taken.
     */
    uint64_t threshold;

    /** Type id bits. */
    int typeIdBits;

    /** Type id mask. */
    uint64_t typeIdMask;
};

#endif // __CPU_EDGE_TOURNAMENT_FRAMEWORK_HH__
